package org.myOrg.spetrum.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class MessageMangementImplement implements MessageMangement {
	public final static int GETINPUTPATH = 0;
	public final static int READOVER = 1;
	public final static int RUN = 2;
	public final static int ADDBUGMODEL = 3;
	public final static int DELETEBUGMODEL = 4;
	public final static int ADDTEMPVALUE = 5;
	public final static int RUNOVER = 6;
	public final static int NOBUGMODEL = 7;
	public final static int CHANGEALOGRITHM = 8;
	public final static int GETOUTPUTPATH = 9;

	public HashMap<Integer, List<Reciver>> recivers;

	public MessageMangementImplement() {
		recivers = new HashMap<Integer, List<Reciver>>();
	}

	@Override
	public void register(Reciver rcv, int messgeType) {
		// TODO Auto-generated method stub
		Integer key = new Integer(messgeType);
		if (!recivers.containsKey(key))
			recivers.put(key, new ArrayList<Reciver>());
		recivers.get(key).add(rcv);
	}

	@Override
	public void dispatchMeesage(Message message) {
		// TODO Auto-generated method stub
		List<Reciver> res = recivers.get(new Integer(message.getType()));
		if (res != null) {			
			Iterator<Reciver> itr = res.iterator();
			while (itr.hasNext()) {
				Thread thread = new Thread(new AsynchronousRun(itr.next(),message));
				thread.start();
			}
		}

	}
	
	class AsynchronousRun implements  Runnable{
		
		private Reciver reciver;
		private Message msg;
		public AsynchronousRun(Reciver reciver,Message msg){
			this.reciver = reciver;
			this.msg = msg;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			reciver.handleMessage(msg);
		}
		
	}

}
